package maa.action.client;

import maa.action.Action;
import maa.action.ActionResult;
import maa.dao.*;
import maa.dao.h2.ClientDAOimpl;
import maa.dao.h2.CourseDAOimpl;
import maa.dao.DAOCommand;
import maa.database.ConnectionPool;
import maa.entity.Course;
import maa.entity.User;
import maa.action.ActionException;
import maa.dao.DAOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MySubscriptions implements Action {
    @Override
    public ActionResult execute(final HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        ActionResult actionResult = new ActionResult();
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        final User user = (User) session.getAttribute("user");
        DAOCommand command = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                ClientDAOimpl clientDAO = daoManager.getClientDAO();
                CourseDAOimpl courseDAO = daoManager.getCourseDAO();
                List<UUID> uuidList = new ArrayList<UUID>();
                List<Course> courseList = new ArrayList<>();
                try {
                    uuidList = clientDAO.findUserSubscriptions(user);
                    courseList = courseDAO.findCoursesById(uuidList);
                } catch (DAOException e) {
                    throw new ActionException("Exception in clientDAO.findUserSubscriptions(user)&courseDAO.findCoursesById(uuidList)");
                }
                return courseList;
            }
        };
        List<Course> courses = (List<Course>) daoManager.executeAndClose(command);
        req.setAttribute("courses", courses);
        actionResult.setResult("account");
        return actionResult;
    }
}
